# coding = utf-8
# !/usr/bin/python

"""

作者 丢丢喵 🚓 内容均从互联网收集而来 仅供交流学习使用 版权归原创者所有 如侵犯了您的权益 请通知作者 将及时删除侵权内容
                    ====================Diudiumiao====================

"""

from Crypto.Util.Padding import unpad
from Crypto.Util.Padding import pad
from urllib.parse import unquote
from Crypto.Cipher import ARC4
from urllib.parse import quote
from base.spider import Spider
from Crypto.Cipher import AES
from datetime import datetime
from bs4 import BeautifulSoup
from base64 import b64decode
import urllib.request
import urllib.parse
import datetime
import binascii
import requests
import base64
import json
import time
import sys
import re
import os

sys.path.append('..')

xurl1 = "https://jhfkdnov21vfd.himdzdwsdz.work:51999"

current_timestamp = int(datetime.datetime.now().timestamp())

headerx = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 8.0; DUK-AL20 Build/HUAWEIDUK-AL20; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044353 Mobile Safari/537.36 MicroMessenger/6.7.3.1360(0x26070333) NetType/WIFI Language/zh_CN Process/tools'
          }

headers = {
    "Accept-Language": "zh-CN,zh;q=0.8",
    "User-Agent": "Mozilla/5.0 (Linux; Android 9; V1938T Build/PQ3A.190705.08211809; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/91.0.4472.114 Safari/537.36;SuiRui/tt/ver=1.1.1",
    "Content-Type": "application/json",
    "Accept": "application/json",
    "deviceId": "49525c5cfd17fb883e01204ae9d37bfb",
    "t": str(current_timestamp),
    "s": "9191b0a3b4c41e6732dbb644bd52d6fc",
    "aut": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzNDYxMzc3IiwiaXNzIjoiIiwiaWF0IjoxNzQzMTgyNzUwLCJuYmYiOjE3NDMxODI3NTAsImV4cCI6MTkwMDg2Mjc1MH0.Mydj2DRmOhD8Y9I6JTRet9XXCqhmpT44YC1dagD78gE",
    "Host": "jhfkdnov21vfd.himdzdwsdz.work:51999",
    "Connection": "Keep-Alive",
    "Accept-Encoding": "gzip, deflate"
          }

pm = ''

class Spider(Spider):
    global xurl1
    global headerx
    global headers

    def getName(self):
        return "首页"

    def init(self, extend):
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def homeContent(self, filter):
        result = {"class": []}

        url = f"{xurl1}/api/yearWeekRange/list"
        response = requests.get(url=url, headers=headers)
        if response.status_code == 200:
            response_data = response.json()
            data = response_data.get('encData')
            detail = self.decrypt(data)
            detail = json.loads(detail)

            js = detail['data']

            for vods in js:

                vodv = vods['weekRanges']

                for vod in vodv:

                    name0 = vod['startTime']

                    name1 = vod['endTime']

                    name = name0 + '@' + name1

                    result["class"].append({"type_id": name, "type_name": name1})

        return result

    def decrypt(self, encrypted_data):
        key = "SmhiR2NpT2lKSVV6STFOaQ=="
        iv = "SmhiR2NpT2lKSVV6STFOaQ=="
        key_bytes = base64.b64decode(key)
        iv_bytes = base64.b64decode(iv)
        encrypted_bytes = base64.b64decode(encrypted_data)
        cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
        decrypted_padded_bytes = cipher.decrypt(encrypted_bytes)
        decrypted_bytes = unpad(decrypted_padded_bytes, AES.block_size)
        return decrypted_bytes.decode('utf-8')

    def homeVideoContent(self):
        pass

    def categoryContent(self, cid, pg, filter, ext):
        result = {}
        videos = []

        url = f"https://api.miaomc.cn/image/get?type=site-image-get&para=1920x1080"
        pict = requests.get(url=url, headers=headerx)
        if pict.status_code == 200:
            pict = pict.json()
            pic = pict.get('url')

        fenge = cid.split("@")

        url = f"{xurl1}/api/video/getByPeriod?page={pg}&pageSize=20&sortType=1&startDate={fenge[0]}&endDate={fenge[1]}"
        response = requests.get(url=url, headers=headers)
        if response.status_code == 200:
            response_data = response.json()
            data = response_data.get('encData')
            detail = self.decrypt(data)
            detail = json.loads(detail)

            js = detail['data']
            for vod in js:

                name = vod['title']

                id = vod['videoId']

                remark = vod['tagTitles']
                if isinstance(remark, list):
                    remark = ', '.join(remark)

                video = {
                    "vod_id": id,
                    "vod_name": name,
                    "vod_pic": pic,
                    "vod_remarks": '' + remark
                        }
                videos.append(video)

        result = {'list': videos}
        result['page'] = pg
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def detailContent(self, ids):
        global pm
        did = ids[0]
        result = {}
        videos = []
        xianlu = ''
        purl = ''

        url = f"{xurl1}/api/video/can/watch?videoId={did}"
        response = requests.get(url=url, headers=headers)
        if response.status_code == 200:
            response_data = response.json()
            data = response_data.get('encData')
            detail = self.decrypt(data)
            detail = json.loads(detail)

            videoUrl = detail.get('videoUrl')

            authKey = detail.get('authKey')

            purl = f"{xurl1}/api/m3u8/decode/authPath?auth_key={authKey}&path={videoUrl}"

            xianlu = '深🌋度'

        videos.append({
            "vod_id": did,
            "vod_play_from": xianlu,
            "vod_play_url": purl
                      })

        result['list'] = videos
        return result

    def playerContent(self, flag, id, vipFlags):

        result = {}
        result["parse"] = 0
        result["playUrl"] = ''
        result["url"] = id
        result["header"] = headerx
        return result

    def searchContentPage(self, key, quick, page):
        result = {}
        videos = []

        url = f"https://api.miaomc.cn/image/get?type=site-image-get&para=1920x1080"
        pict = requests.get(url=url, headers=headerx)
        if pict.status_code == 200:
            pict = pict.json()
            pic = pict.get('url')

        url = f"{xurl1}/api/search/keyWord?pageSize=20&page={page}&searchWord={key}&searchType=1&loadType=1"
        response = requests.get(url=url, headers=headers)
        if response.status_code == 200:
            response_data = response.json()
            data = response_data.get('encData')
            detail = self.decrypt(data)
            detail = json.loads(detail)

            js = detail['videoList']
            for vod in js:

                name = vod['title']

                id = vod['videoId']

                remark = vod['tagTitles']
                if isinstance(remark, list):
                    remark = ', '.join(remark)

                video = {
                    "vod_id": id,
                    "vod_name": name,
                    "vod_pic": pic,
                    "vod_remarks": '' + remark
                        }
                videos.append(video)

        result = {'list': videos}
        result['page'] = page
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def searchContent(self, key, quick, pg="1"):
        return self.searchContentPage(key, quick, '1')

    def localProxy(self, params):
        if params['type'] == "m3u8":
            return self.proxyM3u8(params)
        elif params['type'] == "media":
            return self.proxyMedia(params)
        elif params['type'] == "ts":
            return self.proxyTs(params)
        return None







